package com.example.orchid.paper.task;

import android.content.Context;

import com.example.orchid.paper.Constants;
import com.example.orchid.paper.db.NewsDataSource;
import com.example.orchid.paper.entity.NewsListEntity;
import com.example.orchid.paper.util.GsonUtils;
import com.example.orchid.paper.util.ListUtils;
import com.example.orchid.paper.util.ZhihuUtils;

/**
 * 从服务器下载最新新闻列表，Task
 * Created by Orchid on 2015-10-13.
 */
public class GetLatestNewsTask extends BaseGetNewsTask {

    public GetLatestNewsTask(Context context, ResponseListener responseListener) {
        super(context, responseListener);
    }

    @Override
    protected NewsListEntity doInBackground(String... params) {
        String oldContent = null, newContent = null;

        String date = null;

        NewsListEntity newsListEntity = null;

        try {
            newContent = getUrl(Constants.Url.URL_LATEST);
            newsListEntity = (NewsListEntity) GsonUtils.getEntity(newContent, NewsListEntity.class);

            date = newsListEntity != null ? newsListEntity.date : null;

            oldContent = ((NewsDataSource) getDataSource()).getContent(date);

            isRefreshSuccess = !ListUtils.isEmpty(newsListEntity.stories);
        } catch (Exception e) {
            e.printStackTrace();

            this.isRefreshSuccess = false;
            this.mException = e;
        }

        isContentSame = checkIsContentSame(oldContent, newContent);

        if (isRefreshSuccess && !isContentSame) {
            ((NewsDataSource) getDataSource()).insertOrUpdateNewsList(Constants.NEWS_LIST, date,
                    newContent);
        }

        if (newsListEntity != null) {
            ZhihuUtils.setReadStatus4NewsList(newsListEntity.stories);
        }
        return newsListEntity;
    }
}
